const express = require('express');
const router = express.Router();
const mongodbClient = require('mongodb').MongoClient;
const app = express();
// const cors = require('cors')
// app.use(
//   cors({
//     origin:'http://localhost:8080',//表明该请求来源地址
//     // 'Access-Control-Request-Method':'post',
//     allowedHeaders:['Conten-Type','Authorization']
//   }) 
//  )

const mockData = require('../mock/mockdata')

const dbUrl = 'mongodb://localhost:27017/home'
const collectionName = ["healthyForm", "userForm"]

// 初始化database
// mongodbClient.connect(dbUrl, function (error, db) {
//   if (error) throw error
//   console.log('数据库已存在')
//   const dbBase = db.db('home')
//   dbBase.createCollection(healthyCollectionName, function (error, res) {
//     if (error) throw error
//     console.log('创建集合成功')
//     db.close()
//   })
// })

router.post('/save-form', function (req, res, next) {
  mongodbClient.connect(dbUrl, function (error, db) {
    if (error) throw error
    const dbBase = db.db('home')
    const healthyObj = mockData.form
    dbBase.collection(collectionName[0]).insertOne(healthyObj, function(error, response){
      db.close();
      if (error) throw error;
      console.log('保存healthy成功')
      res.send(true)
    })
  })
});

router.post('/save-user', function (req, res, next) {
  mongodbClient.connect(dbUrl, function (error, db) {
    if (error) throw error
    const dbBase = db.db('home')
    const user = mockData.user
    dbBase.collection(collectionName[1]).insertOne(user, function(error, response){
      db.close();
      if (error) throw error;
      console.log('保存user成功')
      res.send(true)
    })
  })
});

router.get('/form', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  mongodbClient.connect(dbUrl, function (error, db) {
    if (error) throw error
    const dbBase = db.db('home')
    const query = {linkUser: req.query.username}
    dbBase.collection(collectionName[0]).find(query).toArray(function(error, response){
      db.close();
      if (error) throw error;
      console.log('查询数据成功')
      console.log(response)
      res.send(response)
    })
  })
});

router.get('/login', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  const userName = req.query.username
  const pwd = req.query.pwd
  mongodbClient.connect(dbUrl, function (error, db) {
    if (error) throw error
    const dbBase = db.db('home')
    const query = {username: userName}
    dbBase.collection(collectionName[1]).find(query).toArray(function(error, response){
      db.close();
      if (error) throw error;
      if (response[0].pwd == pwd) res.send(true)
      else res.send(false)
    })
  })
});

module.exports = router;
